package com.neuedu.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neuedu.config.PayConfig;
import com.neuedu.service.PayService;
import com.neuedu.util.PayContent;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Service
public class PayServiceImpl implements PayService {
    @Resource
    ObjectMapper objectMapper;
    @Value("${alipay.returnUrl}")
    String returnUrl;
    @Value("${alipay.notifyUrl}")
    String notifyUrl;
    @Override
    public String pay(PayContent payContent) throws JsonProcessingException, AlipayApiException {
        AlipayClient client = new DefaultAlipayClient(
                PayConfig.GATEWAY,
                PayConfig.APPID,
                PayConfig.PRIVATE_KEY,
                "json",
                PayConfig.CHARSET,
                PayConfig.ALIPAY_PUBLIC_KEY,
                PayConfig.SIGN_TYPE
        );
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl(returnUrl);
        request.setNotifyUrl(notifyUrl);
        request.setBizContent(objectMapper.writeValueAsString(payContent));
        return client.pageExecute(request).getBody();
    }

    @Override
    public boolean check(HttpServletRequest request) throws AlipayApiException {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, String> params = new HashMap<>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            if ("open_id".equals(entry.getKey())) {
                continue;
            }
            String value =  String.join(",", entry.getValue());
            params.put(entry.getKey(), value);
        }
        return AlipaySignature.rsaCheckV1(params, PayConfig.ALIPAY_PUBLIC_KEY, PayConfig.CHARSET, PayConfig.SIGN_TYPE);
    }

    @Override
    public boolean updateRegist() {
        return false;
    }
}
